package linkedlist;

import org.junit.jupiter.api.Test;

public class DoubleLinkedList {

    @Test
    public void reversalDoubleNode() {

        DoubleNode DoubleNode1 = new DoubleNode(1);
        DoubleNode DoubleNode2 = new DoubleNode(2);
        DoubleNode DoubleNode3 = new DoubleNode(3);
        DoubleNode DoubleNode4 = new DoubleNode(4);
        DoubleNode1.next = DoubleNode2;
        DoubleNode2.pre = DoubleNode1;
        DoubleNode2.next = DoubleNode3;
        DoubleNode3.pre = DoubleNode2;
        DoubleNode3.next = DoubleNode4;
        DoubleNode4.pre = DoubleNode3;
        System.out.println("=================反转前链表==================");
        System.out.println(printString(DoubleNode1));
        DoubleNode DoubleNode = doReversalDoubleNode(DoubleNode1);
        System.out.println("=================反转后链表==================");
        System.out.println(printString(DoubleNode));
    }

    private DoubleNode doReversalDoubleNode(DoubleNode head) {
        DoubleNode cur = null;
        DoubleNode next = null;
        while (head != null) {
            next = head.next;
            head.pre = next;
            head.next = cur;
            cur = head;
            head = next;
        }
        return cur;
    }

    public String printString(DoubleNode head) {
        String str = "";
        while (head != null) {
            str = str + head.data;
            Integer nextData = head.next == null ? null : head.next.data;
            Integer preData = head.pre == null ? null : head.pre.data;
            str = str + " ==> pre = {" + preData + "} next = {" + nextData + "} ";

            head = head.next;
        }
        return str;
    }

    static class DoubleNode {
        private final Integer data;
        private DoubleNode next;
        private DoubleNode pre;

        public DoubleNode(Integer data) {
            this.data = data;
        }
    }
}
